#!/bin/bash
#description service

source /etc/init.d/functions

FILE_PATH=$0
SERVICE_NAME=${FILE_PATH##*/}

ENV="test"
SERVICE_FILE_NAME='wechat_base.py'
SERVICE_START_LOG='Running on http://0.0.0.0:18000/'

SERVICE_LOG_FILE="$SERVICE_NAME.log"
SERVICE_PS=''
SERVICE_PID=0

if [[ ! -z "$(ls /var/log/${SERVICE_LOG_FILE}.*)" ]];then
  rm -f $(find /var/log/${SERVICE_LOG_FILE}.* -mtime +10)
fi

check_service(){
  SERVICE_PS=$(ps aux | grep "$SERVICE_FILE_NAME" | grep -v 'grep')
  SERVICE_PID=$(echo ${SERVICE_PS} | awk '{print $2}')
}

start(){
  check_service
  if [[ ! -z "$SERVICE_PS" ]];then
    action "$SERVICE_NAME is started, pid: $SERVICE_PID"
    return 0
  else
    if [[ -f "/var/log/$SERVICE_LOG_FILE" ]];then
      NOW=$(date "+%Y%m%d%H%M%S")
      echo "rename log file to $SERVICE_LOG_FILE.$NOW"
      mv /var/log/${SERVICE_LOG_FILE} /var/log/"$SERVICE_LOG_FILE.$NOW"
    fi
    echo -n "$SERVICE_NAME is starting ..."
    python3 -u /usr/etc/${SERVICE_FILE_NAME} >> /var/log/${SERVICE_LOG_FILE} 2>&1 &
    START_TIMES=0
    for i in {1..100};do
      let START_TIMES=$START_TIMES+1
      started_log=$(grep "$SERVICE_START_LOG" /var/log/${SERVICE_LOG_FILE})
      if [[ ! -z "$started_log" ]];then
        echo ""
        echo "$started_log"
        status
        return 0
      else
        sleep 2
        echo -n " ..."
        if [[ ${START_TIMES} -gt 5 ]]; then
            tail -n 10 /var/log/${SERVICE_LOG_FILE}
        fi
      fi
    done
  fi
}

stop(){
  check_service
  if [[ -z "$SERVICE_PS" ]];then
    action "$SERVICE_NAME is stopped"
  else
    echo "stopping $SERVICE_NAME (pid: $SERVICE_PID) ..."
    kill -9 ${SERVICE_PID}
    for i in {1..100};do
      check_service
      test -z "$SERVICE_PS" && action "$SERVICE_NAME is stopped" && return 0 || echo -n " ..."
      sleep 2
    done
  fi
}

status(){
  check_service
  if [[ ! -z "$SERVICE_PS" ]];then
    action "$SERVICE_NAME is running, pid: $SERVICE_PID"
  else
    action "$SERVICE_NAME is stopped" /bin/false
  fi
}


case $1 in
start)
    start
    ;;
stop)
    stop
    ;;
status)
    status
    ;;
restart)
    stop
    start
    ;;

*)
    echo "usage: $SERVICE_NAME status | stop | start | restart "
    ;;
esac